<template>
  <div class="requirement-analysis">
    <h3>需求文档解析</h3>
    
    <a-card title="文档配置" style="margin-bottom: 20px;">
      <a-form layout="vertical">
        <a-row :gutter="16">
          <a-col :span="16">
            <a-form-item label="需求文档地址">
              <a-input v-model:value="formState.url" placeholder="请输入Confluence页面地址" />
            </a-form-item>
          </a-col>
          <a-col :span="8" style="display: flex; align-items: flex-end;">
            <a-button type="primary" @click="analyzeRequirement" :loading="loading">开始解析</a-button>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="Confluence 用户名">
              <a-input v-model:value="formState.username" placeholder="默认: gushan" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="Confluence 密码">
              <a-input-password v-model:value="formState.password" placeholder="默认: 123456" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <div v-if="result">
      <a-alert
        v-if="result.pageTitle"
        :message="`解析成功: ${result.pageTitle}`"
        type="success"
        show-icon
        style="margin-bottom: 20px;"
      />

      <a-card title="结构化结果" style="margin-bottom: 20px;" v-if="result.structure">
        <a-tabs>
          <a-tab-pane v-for="(areaData, areaName) in result.structure" :key="areaName" :tab="areaMap[areaName] || areaName">
            <a-tabs type="card" size="small">
              <!-- 查询区域 Tab -->
              <a-tab-pane 
                v-if="areaData.search && areaData.search.length > 0" 
                key="search" 
                tab="查询条件"
              >
                <a-table 
                  :columns="columns" 
                  :data-source="areaData.search" 
                  :pagination="false" 
                  rowKey="label"
                  size="small"
                >
                   <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'required'">
                      <a-tag :color="record.required ? 'red' : 'green'">
                        {{ record.required ? '必填' : '非必填' }}
                      </a-tag>
                    </template>
                    <template v-if="column.key === 'defaultDisplay'">
                       <a-tag :color="record.isDefaultShow ? 'blue' : ''">
                        {{ record.isDefaultShow ? '是' : '否' }}
                      </a-tag>
                    </template>
                  </template>
                </a-table>
              </a-tab-pane>

              <!-- 列表区域 Tab -->
              <a-tab-pane 
                v-if="areaData.table && areaData.table.length > 0" 
                key="table" 
                tab="列表字段"
              >
                <a-table 
                  :columns="columns" 
                  :data-source="areaData.table" 
                  :pagination="false" 
                  rowKey="label"
                  size="small"
                >
                   <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'required'">
                      <a-tag :color="record.required ? 'red' : 'green'">
                        {{ record.required ? '必填' : '非必填' }}
                      </a-tag>
                    </template>
                     <template v-if="column.key === 'defaultDisplay'">
                       <a-tag :color="record.isDefaultShow ? 'blue' : ''">
                        {{ record.isDefaultShow ? '是' : '否' }}
                      </a-tag>
                    </template>
                  </template>
                </a-table>
              </a-tab-pane>

              <!-- 表单区域 Tab -->
              <a-tab-pane 
                v-if="areaData.form && areaData.form.length > 0" 
                key="form" 
                tab="表单字段"
              >
                <a-table 
                  :columns="columns" 
                  :data-source="areaData.form" 
                  :pagination="false" 
                  rowKey="label"
                  size="small"
                >
                   <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'required'">
                      <a-tag :color="record.required ? 'red' : 'green'">
                        {{ record.required ? '必填' : '非必填' }}
                      </a-tag>
                    </template>
                     <template v-if="column.key === 'defaultDisplay'">
                       <a-tag :color="record.isDefaultShow ? 'blue' : ''">
                        {{ record.isDefaultShow ? '是' : '否' }}
                       </a-tag>
                    </template>
                  </template>
                </a-table>
              </a-tab-pane>
            </a-tabs>
          </a-tab-pane>
        </a-tabs>
      </a-card>

    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { message } from 'ant-design-vue';
import { config } from '../config.js';

const loading = ref(false);
const activeKey = ref([]);
const result = ref(null);

const areaMap = {
  header: '表头区域',
  body: '表体区域'
};

const formState = reactive({
  url: 'http://192.168.2.200:8090/pages/viewpage.action?pageId=75667598',
  username: 'gushan',
  password: '123456'
});

const columns = [
  {
    title: '字段文字 (Label)',
    dataIndex: 'label',
    key: 'label',
    width: 150
  },
  {
    title: '必填',
    dataIndex: 'required',
    key: 'required',
    width: 80
  },
  {
    title: '组件类型',
    dataIndex: 'componentType',
    key: 'componentType',
    width: 120
  },
   {
    title: '默认显示',
    dataIndex: 'defaultDisplay',
    key: 'defaultDisplay',
    width: 100
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  }
];

const analyzeRequirement = async () => {
  if (!formState.url) {
    message.warning('请输入文档地址');
    return;
  }

  loading.value = true;
  result.value = null;
  activeKey.value = [];

  try {
    const response = await fetch(`${config.domain}/api/analyze-requirement`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formState)
    });

    const data = await response.json();

    if (data.success) {
      result.value = data.data;
      // 默认展开第一个
      if (result.value.sections.length > 0) {
        activeKey.value = [0];
      }
      message.success('解析成功');
    } else {
      message.error(data.message || '解析失败');
    }
  } catch (error) {
    console.error('Analysis error:', error);
    message.error('解析请求失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

const copyToClipboard = () => {
  if (!result.value) return;
  const text = JSON.stringify(result.value, null, 2);
  navigator.clipboard.writeText(text).then(() => {
    message.success('已复制到剪贴板');
  }).catch(err => {
    message.error('复制失败');
  });
};
</script>

<style scoped>
.requirement-analysis {
  padding: 20px;
}
</style>
